<template>
  <main class="login-container">
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field v-model="formData.username" name="用户名" label="用户名" placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]" />
        <van-field v-model="formData.password" type="password" name="密码" label="密码" placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]" />
        <van-field v-model="formData.code" name="code" label="验证码" placeholder="验证码">
          <template #button>
            <img @click="changeCode" style="width: 100px" :src="codeImg" alt="code" />
          </template>
        </van-field>
        <van-field v-model="formData.google" name="google" label="谷歌验证码" placeholder="请输入谷歌验证码（未绑定不用输入）">
        </van-field>
      </van-cell-group>
      <div style="margin: 16px; display: flex; justify-content: space-between">
        <van-button round type="primary"> 在线咨询 </van-button>
        <van-button icon="upgrade" round type="primary" native-type="submit"> 登录 </van-button>
      </div>
    </van-form>
  </main>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { useUserStore } from '@/stores/user'
import { useRouter, useRoute } from 'vue-router'
import { GetCodeApi } from '@/apis/system'
import { showNotify } from 'vant'
import { removeCache } from '@/utils/cache'

const { login, xnLogin } = useUserStore()
const router = useRouter()
const route = useRoute()
const codeImg = ref()

onMounted(async () => {
  const virtualToken = route.query.virtualToken
  if (virtualToken) {
    removeCache('virtualToken')
    const data = await xnLogin(virtualToken)
    if (data) {
      router.push('/')
      return
    }
  }

  codeImg.value = await GetCodeApi()
})

const formData = ref({
  username: '',
  password: '',
  keep: '1',
  code: '',
  google: ''
})

function onSubmit() {
  login(
    formData.value.username,
    formData.value.password,
    formData.value.code,
    formData.value.google
  )
    .then(() => {
      router.push('/')
    })
    .catch((res) => {
      if (res.code === 201) {
        showNotify({ type: 'danger', message: res.msg })
      }

      changeCode()
    })
}

async function changeCode() {
  formData.value.code = ''
  codeImg.value = await GetCodeApi()
}

async function getCaptcha() {
  codeImg.value = await GetCodeApi()
}
</script>

<style lang="less" scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
